package org.nanotek.tika.tests.index;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.nanotek.cms.domain.lucene.FieldStat;
import org.nanotek.cms.domain.lucene.Index;
import org.nanotek.cms.domain.lucene.ScoreDocument;
import org.nanotek.cms.domain.lucene.TermStats;
import org.nanotek.lucene.index.search.IndexSearchService;
import org.nanotek.lucene.index.search.IndexType;
import org.nanotek.lucene.query.ContextKeys;
import org.nanotek.lucene.query.QueryContext;
import org.nanotek.lucene.query.QueryResult;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobExecutionNotRunningException;
import org.springframework.batch.core.launch.NoSuchJobException;
import org.springframework.batch.core.launch.NoSuchJobExecutionException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class IndexServiceTest {

	private static ClassPathXmlApplicationContext ctx;

	/**
	 * @param args
	 * @throws IOException 
	 * @throws JobParametersInvalidException 
	 * @throws JobInstanceAlreadyCompleteException 
	 * @throws JobRestartException 
	 * @throws JobExecutionAlreadyRunningException 
	 * @throws NoSuchJobException 
	 * @throws JobExecutionNotRunningException 
	 * @throws NoSuchJobExecutionException 
	 */
	public static void main(String[] args) throws Exception  {

		ctx = new ClassPathXmlApplicationContext(new String[] {"base-index-config/index-service-context.xml"});
		IndexSearchService searchService = (IndexSearchService) ctx.getBean("indexSearchService"); 
		List<Index> indexes = searchService.getIndexList(); 
		for (Index index : indexes) 
		{ 
			index.setIndexType(IndexType.NMAPDIRECTORY);
			QueryContext queryContext = new QueryContext(); 
			queryContext.setMaxHits(100);
			queryContext.put(ContextKeys.CURRENT_INDEX, index);
			queryContext.setSearchPhrase( "solr AND apache");
			//TODO set target fields outside the results provider class
			queryContext.put(ContextKeys.TARGET_FIELD, "TextData");
			List<TermStats> termStats = searchService.getTermStats(index, new String[]{"solr","apache", "lucene" , "nutch"});
			for (TermStats stat : termStats) 
			{ 
				System.out.print(stat.getTerm().text());
				System.out.println("\t");
				System.out.print("Term Frequence :" + stat.getTermFrequency());
				System.out.print("\t");
				System.out.print("Total Term Frequence :" + stat.getTotalTermFrequency());
				System.out.print("\t");
				System.out.print(stat.getTerm().text());
				System.out.println("\t");
			}
			FieldStat fieldStat = searchService.getFieldStat(index, "TextData");
			System.out.print("Field Name:" + fieldStat.getFieldName());
			System.out.print("\t");
			System.out.print("Document Count :" + fieldStat.getDocCount());
			System.out.print("\t");
			System.out.print("SumDocFrequency: " + fieldStat.getSumDocFrequency());
			System.out.print("\t");
			System.out.print("SumTotalTermFreq :" + fieldStat.getSumTotalTermFreq());
			System.out.print("\t");
			System.out.print("DocFrequency() :" + fieldStat.getDocFrequency());
			System.out.println("\t");
			System.out.print("Has Positions :" + fieldStat.hasPositions());
			System.out.print("\t");
			System.out.print("Has Payload :" + fieldStat.hasPayloads());
			System.out.print("\t");
			System.out.print("Has Offset :" + fieldStat.hasOffsets());
			System.out.println("\t");			
//			printResults (queryContext);
			System.out.println(indexes.size());
		}

	}

	@SuppressWarnings("unused")
	private static void printResults(QueryContext queryContext) throws Exception {
		IndexSearchService searchService = (IndexSearchService) ctx.getBean("indexSearchService");
		QueryResult queryResult = searchService.searchIndex(queryContext);
		System.out.println("Results size " + queryResult.getDocuments().size());
		printResult(queryResult.getDocuments()); 
		TopDocs topDocs = queryResult.getTopDocs();
		while (topDocs !=null) 
		{ 
			if (topDocs.scoreDocs !=null && topDocs.scoreDocs.length > 0){ 
				ScoreDoc scoreDoc = topDocs.scoreDocs[topDocs.scoreDocs.length -1]; 
				queryContext.put(ContextKeys.LAST_SCORED_DOC, scoreDoc); 
				queryResult = searchService.searchIndex(queryContext);
				System.out.println("Results size " + queryResult.getDocuments().size());
				printResult(queryResult.getDocuments()); 
				topDocs = queryResult.getTopDocs();
			}else { 
				topDocs = null; 
			}
		}
	}

	private static void printResult(List<ScoreDocument> documents) {
		if (documents !=null && documents.size()>0){ 
			List<IndexableField> fields = documents.get(0).getDocument().getFields();
			for (IndexableField field : fields) 
			{ 
				System.out.println(field.name());
			}
			for (ScoreDocument scoreDoc : documents) 
			{ 
				Document document = scoreDoc.getDocument(); 
				ScoreDoc sc = scoreDoc.getScoreDoc(); 
				System.out.println(document.getField("file_location").stringValue()+ "\t" + new Date(new Long(document.getField("modified").stringValue())).toString() + "\t" + sc.score);
			}
		}
	}

}
